#include "globalevents.h"

GlobalEvents::GlobalEvents()
        : m_interface("GlobalEvents Interface")
{
        m_interface.initState();

        if(m_interface.loadFile("data/globalevents/GlobalEvents.lua"))
        {
                std::cout << std::endl << "> Error: Unable to load the main global events file." << std::endl << std::endl;
        }
}

GlobalEvents::~GlobalEvents()
{
        //
}

bool GlobalEvents::ExecuteEvent(const char* Event)
{
        if(!m_interface.reserveScriptEnv())
        {
                std::cout << std::endl << "> Error: Call stack overflow executing the GlobalEvent " << Event << std::endl << std::endl;
                return false;
        }

        ScriptEnviroment* env = m_interface.getScriptEnv();
        env->setScriptId(1, &m_interface);

        lua_State* L = m_interface.getLuaState();

        lua_getglobal(L, Event);
        if(!lua_isfunction(L, -1))
        {
                std::cout << std::endl << "< [GlobalEvents::ExecuteEvent(Event = " << Event << "Smile] > " << std::endl << "> Error: " << Event << " does not name a callable function." << std::endl << std::endl;
                return false;
        }

        m_interface.callFunction(0);

        m_interface.releaseScriptEnv();

        return true;
}

bool GlobalEvents::ExecuteStartUp()
{
        if(!ExecuteEvent("StartUp"))
        {
                std::cout << std::endl << "> Unable to execute GlobalEvent: StartUp" << std::endl << std::endl;
                return false;
        }

        return true;
}
